package com.hzeng.util;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

import au.com.bytecode.opencsv.CSVReader;

public class ConvertionDialog {
	JDialog dialog = null;
	private static JFileChooser fileChooser = null;
	List<File> convertFiles = null;
	List<File> resultFiles = null;
	
	JScrollPane fileListScrollPane = null;
	JList fileList = null;
	
	JScrollPane resultListScrollPane = null;
	JList resultList = null;
	
	JPanel dialogJPanel = null;
	JButton selectFileButton = null;
	
	JButton deleteFileButton = null;
	JButton deleteAllFilesButton = null;
	
	JButton convertButton = null;
	
	JButton deleteAllResultButton = null;
	JButton quitButton = null;
	
	JFrame container = null;
	
	private static final int LIST_WIDTH = 220;
	private static final int LIST_HEIGHT = 200;
	
	private static final int BUTTON_WIDTH = 80;
	private static final int BUTTON_HEIGHT = 30;

	public ConvertionDialog(JFrame container) {
		dialog = new JDialog(container,"Convertion list",true);
		dialogJPanel = new JPanel();
		dialogJPanel.setLayout(new GridBagLayout());
		dialog.setContentPane(dialogJPanel);
		
		GridBagConstraints constraints = new GridBagConstraints();
		constraints.fill = GridBagConstraints.NONE;
		constraints.anchor = GridBagConstraints.CENTER;
		constraints.weightx = 7;
		constraints.weighty = 8;
		
		
		initListPanel();
		initButtons();
		
		add(selectFileButton,constraints,1,0,1,1);
		add(fileListScrollPane,constraints,0,1,3,5);
		add(deleteFileButton,constraints,0,6,1,1);
		add(deleteAllFilesButton,constraints,2,6,1,1);
		
		add(convertButton,constraints,3,3,1,1);
		add(resultListScrollPane,constraints,4,1,3,5);
		add(deleteAllResultButton,constraints,6,6,1,1);
		
		add(quitButton,constraints,3,7,1,1);
		
		
		
		dialog.setResizable(false);
		dialog.setLocation(300, 250);
		dialog.setPreferredSize(new Dimension(600, 400));
		dialog.setSize(new Dimension(600, 400));
		dialog.pack();
		dialog.setVisible(true);
	//	dialog.setBounds(100,100,400,340);
		dialog.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
	}

	public void add(Component c,GridBagConstraints constraints, int x,int y,int w,int h) {
		constraints.gridx = x;
		constraints.gridy = y;
		constraints.gridwidth = w;
		constraints.gridheight = h;
		
		dialogJPanel.add(c,constraints);
	}
	
	public void initButtons() {
		convertFiles = new ArrayList<File>();
		resultFiles = new ArrayList<File>();
		
		fileChooser = new JFileChooser();
	    fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
	    fileChooser.setMultiSelectionEnabled(true);
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
     	fileChooser.setFileFilter(new myFileFilter(new String[] { ".txt",".csv" },"*.txt,*.csv"));
		
		selectFileButton = new JButton("Select..");
		selectFileButton.setPreferredSize(new Dimension(BUTTON_WIDTH, BUTTON_HEIGHT));
		selectFileButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				int retval = fileChooser.showSaveDialog(dialog);
            	if(retval == JFileChooser.APPROVE_OPTION) {
            		File[] files = fileChooser.getSelectedFiles();
            		DefaultListModel listModel = (DefaultListModel) fileList.getModel();
            		listModel.removeAllElements();
            		for (int i = 0; i < files.length; i++) {
						File tempFile = files[i];
						if (tempFile.isFile()) {
							convertFiles.add(tempFile);
							listModel.addElement(tempFile.getName());
						}
					}
            		fileList.updateUI();
            	}
			}
		});
		convertButton = new JButton("Convert");
		convertButton.setPreferredSize(new Dimension(BUTTON_WIDTH, BUTTON_HEIGHT));
		convertButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				DefaultListModel listModel = (DefaultListModel) fileList.getModel();
				
				if (listModel == null || listModel.getSize() <= 0) {
					JOptionPane.showMessageDialog(null, "warning:there is no file to convert!");
					
					return;
				}
				
				deleteAllResult();
				
				
				for (int i = 0; i < convertFiles.size(); i++) {
					File tempFile = convertFiles.get(i);
					if (tempFile.exists()) {
						String[] header = CSVUtil.readHeader(tempFile);
						CSVReader reader = CSVUtil.readFile(tempFile);
						List<Program> programs = null;
						//init capacity of List to optimize the performance
						if (tempFile.length() < 1024) {
							programs = new ArrayList<Program>();
						}else if (tempFile.length() < 1024 * 1024) {
							programs = new ArrayList<Program>(1000);
						}else if (tempFile.length() < 1024 * 1024 * 1024) {
							programs = new ArrayList<Program>(100000);
						}
						
						
						long rowNum = 0;
						String[] rowData = null;
						
						while ((rowData = CSVUtil.readRowData(reader)) != null) {
							if (rowNum == 0) {
								
							}else {
								Program pro = new Program();
								for (int j = 0; j < header.length; j++) {
									if (header[j].equals(Constants._TIME)) {
										
										try {
											pro.setTimestamp(new Long(rowData[j]));
										} catch (Exception e2) {
											pro.setTimestamp(new Date().getTime());
										}
									}else if (header[j].endsWith(Constants._CPU)) {
										try {
											pro.setCpu(new Double(rowData[j]));
										} catch (Exception e2) {
											pro.setCpu(0);
										}
										
									}else if (header[j].endsWith(Constants._VM)) {
										
										try {
											pro.setVirtualMemory(0);
										} catch (Exception e2) {
											
										}
									}else if (header[j].endsWith(Constants._TOTAL_MEMORY)) {
										
										try {
											pro.setTotalMemory(new Double(rowData[j]));
										} catch (Exception e2) {
											pro.setTotalMemory(0);
										}
									}else if (header[j].endsWith(Constants._MEMORY)) {
										
										try {
											pro.setMemory(new Double(rowData[j]));
										} catch (Exception e2) {
											pro.setMemory(0);
										}
									}else if (header[j].endsWith(Constants._READ)) {
										
										try {
											pro.setRead(new Double(rowData[j]));
										} catch (Exception e2) {
											pro.setRead(0);
										}
									}else if (header[j].endsWith(Constants._WRITE)) {
										
										try {
											pro.setWrite(new Double(rowData[j]));
										} catch (Exception e2) {
											pro.setWrite(0);
										}
									}
								}
								programs.add(pro);
							}
							rowNum++;
						}
							
						MyTimeSeriesChartUtil chartUtil = MyTimeSeriesChartUtil.getInstance();
						chartUtil.setPrograms(programs);
						chartUtil.setSaveFile(tempFile);
						List<File> tempFiles = chartUtil.buildImagebyFile();
						
						//list all images to JList
						DefaultListModel resultListModel = (DefaultListModel) resultList.getModel();
						for (int k = tempFiles.size() - 1; k >= 0; k--) {
							resultFiles.add(tempFiles.get(k));
							resultListModel.addElement(tempFiles.get(k).getName());
						}
					}
					
					
					
				}
				
			}
		});


		deleteFileButton = new JButton("Delete");
		deleteFileButton.setPreferredSize(new Dimension(BUTTON_WIDTH, BUTTON_HEIGHT));
		deleteFileButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				
            	DefaultListModel listModel = (DefaultListModel) fileList.getModel();
            	int[] selectRows = fileList.getSelectedIndices();
            	Arrays.sort(selectRows);
            	
				for (int i = selectRows.length - 1; i >= 0; i--) {
					listModel.remove(selectRows[i]);
					convertFiles.remove(selectRows[i]);
					
				}
				fileList.updateUI();
				
			}
		});
		
		deleteAllFilesButton = new JButton("Delete All");
		deleteAllFilesButton.setPreferredSize(new Dimension(BUTTON_WIDTH, BUTTON_HEIGHT));
		deleteAllFilesButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				
				deleteAllTargetFiles();
			}
		});
		
		
		deleteAllResultButton = new JButton("Delete All");
		deleteAllResultButton.setPreferredSize(new Dimension(BUTTON_WIDTH, BUTTON_HEIGHT));
		deleteAllResultButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				
				deleteAllResultFiles();
			}
		});
		
		quitButton = new JButton("Quit");
		quitButton.setPreferredSize(new Dimension(BUTTON_WIDTH, BUTTON_HEIGHT));
		quitButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				dialog.dispose(); 
			}
		});
	}
	
	public void deleteAllResult() {
		DefaultListModel listModel = (DefaultListModel) resultList.getModel();
    	listModel.removeAllElements();
    	resultList.updateUI();
    	if (resultFiles == null || resultFiles.size() < 1) {
			return;
		}
    	resultFiles.clear();
	}
	
	public void deleteAllResultFiles() {
		DefaultListModel listModel = (DefaultListModel) resultList.getModel();
    	listModel.removeAllElements();
    	resultList.updateUI();
    	if (resultFiles == null || resultFiles.size() < 1) {
			return;
		}
    	for (int i = resultFiles.size() - 1; i >= 0; i--) {
    		
    		try {
    			resultFiles.get(i).delete();
			} catch (Exception e) {
			}
		}
    	resultFiles.clear();
	}
	
	public void deleteAllTargetFiles() {
		DefaultListModel listModel = (DefaultListModel) fileList.getModel();
		listModel.removeAllElements();
		fileList.updateUI();
		convertFiles.clear();
	}
	
	public void initListPanel() {
		fileList = new JList(new DefaultListModel());
		fileList.setBorder(BorderFactory.createTitledBorder("To convert file list:"));
	    
	    fileListScrollPane = new JScrollPane(fileList);
	    fileListScrollPane.setPreferredSize(new Dimension(LIST_WIDTH, LIST_HEIGHT));
	    fileListScrollPane.setSize(new Dimension(LIST_WIDTH, LIST_HEIGHT));
	    
	    
	    
	    resultList = new JList(new DefaultListModel());
	    resultList.setBorder(BorderFactory.createTitledBorder("Result list:"));
		    
	    resultListScrollPane = new JScrollPane(resultList);
	    resultListScrollPane.setPreferredSize(new Dimension(LIST_WIDTH, LIST_HEIGHT));
	    resultListScrollPane.setSize(new Dimension(LIST_WIDTH, LIST_HEIGHT));
	    
	}
	
	public static void main(String[] args) {
		
	}

}